# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response, get_object_or_404, redirect
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.template import RequestContext
from django.core.mail import send_mail
from django.contrib.auth.decorators import login_required
from django.contrib import auth
from django.contrib.auth.decorators import user_passes_test
from getdebt.advice.views import advices
import datetime
from django.views.decorators.cache import never_cache
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.sites.models import Site, RequestSite
from django.conf import settings

def userinfo(request):
    "информация об авторизации для шаблона."
    if request.user.is_authenticated():
        user_login=True
        user_name=request.user.first_name+' '+request.user.last_name
        user = request.user
    else:
        user_login=False
        user_name=''
    return {'user':request.user,'user_login':user_login,'user_name':user_name}

def login(request, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME):
    "Displays the login form and handles the login action."
    redirect_to = request.REQUEST.get(redirect_field_name, '')
    if request.method == "POST":
        form = AuthenticationForm(data=request.POST)
        if form.is_valid():
            redirect_to = request.POST['redirect_to']
            # Light security check -- make sure redirect_to isn't garbage.
            if not redirect_to or '//' in redirect_to or ' ' in redirect_to:
                redirect_to = settings.LOGIN_REDIRECT_URL
            from django.contrib.auth import login
            login(request, form.get_user())
            if request.session.test_cookie_worked():
                request.session.delete_test_cookie()
            return redirect(redirect_to)
    else:
        form = AuthenticationForm(request)
    request.session.set_test_cookie()
    if Site._meta.installed:
        current_site = Site.objects.get_current()
    else:
        current_site = RequestSite(request)
    return render_to_response(template_name, {
        'form': form,
        'redirect_field_name': redirect_field_name,
        'site': current_site,
        'site_name': current_site.name, 'advices_list': advices(request, 'login'),
    }, context_instance=RequestContext(request, processors = [userinfo]))
login = never_cache(login)

def logout(request):
    auth.logout(request)
    log_out=True
    dictionary={}
    dictionary['advices_list'] = advices(request, 'login')
    return render_to_response('registration/logout.html', dictionary)

@user_passes_test(lambda u: u.is_authenticated(),login_url="/login/")
def profile(request):
    dictionary={}
    dictionary['advices_list'] = advices(request, 'cabinet')
    return render_to_response('registration/start_profile.tpl', dictionary, context_instance=RequestContext(request, processors = [userinfo]))
    
def user_can_add(user):
    #переписать!!!
    return user.is_authenticated()

def user_can_view(user):
    #переписать!!!
    return user.is_authenticated()

@user_passes_test(user_can_add, login_url="/login/")
def user_debtors(request):
    user_debtors = Debtor.objects.filter(client__user__exact=request.user).order_by('name')
    return {'user_debtors':user_debtors}
